package cn.labbook.bluetooth.controller;


import cn.labbook.bluetooth.common.MyPage;
import cn.labbook.bluetooth.common.ResultDto;
import cn.labbook.bluetooth.common.TokenManager;
import cn.labbook.bluetooth.constant.AdminConstant;
import cn.labbook.bluetooth.constant.AmmeterConstant;
import cn.labbook.bluetooth.entity.*;
import cn.labbook.bluetooth.entity.StaticsEntity.ManufactorStatistics;
import cn.labbook.bluetooth.service.*;
import cn.labbook.bluetooth.util.GenerateIdUtils;
import cn.labbook.bluetooth.util.MD5Utils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lonzy
 * @since 2019-03-26
 */
@Controller
@RequestMapping("//admin")
public class AdminController extends AbstractController {

    @Autowired
    private IAdminService adminService;
    @Autowired
    private IAdminResService adminResService;
    @Autowired
    private IAmmeterService ammeterService;
    @Autowired
    private IConstantService constantService;


    @RequestMapping({"add"})
    @ResponseBody
    public ResultDto addEntity(Admin admin) {
        List<String> list = new ArrayList<>();
        admin.setCreateTime(new Date());
        admin.setValid(AdminConstant.VALID);
        admin.setPassword(MD5Utils.string2MD5(admin.getPassword()));
        if (TokenManager.getToken().getAdmin().getAdminStatus() == AdminConstant.position.MANUFACTURERS) {
            admin.setManufacturersId(TokenManager.getToken().getAdminId());
            admin.setAdminStatus(AdminConstant.position.DEALER);
            admin.setAdminId(GenerateIdUtils.get32Varchar());
            LambdaQueryWrapper<Constant> lambda = new QueryWrapper<Constant>().lambda();
            lambda.eq(Constant::getK, "serverPrice");
            Constant constant = (Constant)this.constantService.getOne(lambda);
            admin.setPayRate(constant.getV());
            list.add("002");
            list.add("002-002");
            list.add("003");
            list.add("003-001");
            list.add("003-002");
        } else if (TokenManager.getToken().getAdmin().getAdminStatus() == AdminConstant.position.ZK) {
            admin.setAdminStatus(AdminConstant.position.MANUFACTURERS);
            list.add("001");
            list.add("001-001");
            list.add("001-002");
            list.add("002");
            list.add("002-001");
        }
        for (int i = 0; i < list.size(); i++) {
            AdminRes adminRes = new AdminRes();
            adminRes.setAdminId(admin.getAdminId());
            adminRes.setResourceId(list.get(i));
            this.adminResService.save(adminRes);
        }
        boolean save = this.adminService.save(admin);
        return save? success(save) : fail();
    }

    @RequestMapping("register")
    @ResponseBody
    public ResultDto register(Admin admin){
        LambdaQueryWrapper<Admin> lambda = new QueryWrapper<Admin>().lambda();
        lambda.eq(Admin::getAccountNumber,admin.getAccountNumber());
        Admin one = adminService.getOne(lambda);
        if(one != null){
            return fail("账号已重复，请重新输入");
        }
        LambdaQueryWrapper<Admin> lambda1 = new QueryWrapper<Admin>().lambda();
        lambda1.eq(Admin::getMobilephone,admin.getMobilephone());
        Admin one1 = adminService.getOne(lambda1);
        if(one1 != null){
            return fail("手机号已重复，请重新输入");
        }
        LambdaQueryWrapper<Admin> lambda2 = new QueryWrapper<Admin>().lambda();
        lambda2.eq(Admin::getIdentity,admin.getIdentity());
        Admin one2 = adminService.getOne(lambda2);
        if(one2 != null){
            return fail("身份证号已重复，请重新输入");
        }

        List<String> list = new ArrayList<>();
        list.add("004");
        list.add("004-001");
        list.add("004-002");
        admin.setCreateTime(new Date());
        admin.setAdminId(GenerateIdUtils.get32Varchar());
        admin.setValid(AdminConstant.VALID);
        admin.setPassword(MD5Utils.string2MD5(admin.getPassword()));
        for (int i = 0;i<list.size();i++) {
            AdminRes adminRes = new AdminRes();
            adminRes.setAdminId(admin.getAdminId());
            adminRes.setResourceId(list.get(i));
            adminResService.save(adminRes);
        }
        boolean save = adminService.save(admin);
        return save? success(save) : fail();
    }
    @RequestMapping("edit")
    @ResponseBody
    public ResultDto editEntity(Admin admin){
        admin.setModifyTime(new Date());
        boolean b = adminService.updateById(admin);
        return b? success(b) : fail();
    }

    @RequestMapping("delete")
    @ResponseBody
    public ResultDto deleteEntity(Admin admin){
        LambdaQueryWrapper<Ammeter> lambda = new QueryWrapper<Ammeter>().lambda();
        lambda.eq(Ammeter::getAdminId,admin.getAdminId());
        if(ammeterService.count(lambda)>0){
            return fail("该经销商存在绑定电表，不可删除");
        }
        LambdaQueryWrapper<Ammeter> lambda2 = new QueryWrapper<Ammeter>().lambda();
        lambda.eq(Ammeter::getManufacturersId,admin.getAdminId());
        if(ammeterService.count(lambda2)>0){
            return fail("该厂家存在绑定经销商，不可删除");
        }
        admin.setModifyTime(new Date());
        admin.setValid(AdminConstant.NOTVALID);
        boolean b = adminService.updateById(admin);
        return b? success(b) : fail();
    }


    @RequestMapping("page")
    @ResponseBody
    public ResultDto page(Page<Admin> page, Admin admin) {
        LambdaQueryWrapper<Admin> lambda = new QueryWrapper<Admin>().lambda();

        lambda.ne(Admin::getValid,AdminConstant.NOTVALID);
        if (StringUtils.isNotBlank(admin.getAdminName())) {
            lambda.like(Admin::getAdminName, admin.getAdminName());
        }
        if (admin.getAdminStatus()!=null) {
            lambda.eq(Admin::getAdminStatus, admin.getAdminStatus());
        }
        if(TokenManager.getToken().getAdmin().getAdminStatus()==AdminConstant.position.MANUFACTURERS){
            lambda.eq(Admin::getManufacturersId,TokenManager.getToken().getAdminId());
        }
        if(TokenManager.getToken().getAdmin().getAdminStatus()==AdminConstant.position.ZK){
            lambda.eq(Admin::getAdminStatus,AdminConstant.position.MANUFACTURERS);
        }
        IPage<Admin> result = adminService.page(page, lambda);
        if(TokenManager.getToken().getAdmin().getAdminStatus()==AdminConstant.position.ZK){
            result.getRecords().forEach(admin1 -> {
                ManufactorStatistics manufactorStatistics = ammeterService.getStatisticsByManufactor(admin1.getAdminId());
                admin1.setMonthtotal(manufactorStatistics.getMonthtotal());
                admin1.setTotal(manufactorStatistics.getTotal());
            });
        }
        if(TokenManager.getToken().getAdmin().getAdminStatus()==AdminConstant.position.MANUFACTURERS){
            result.getRecords().forEach(admin2 -> {
                ManufactorStatistics manufactorStatistics = ammeterService.getStatisticsByDealer(admin2.getAdminId());
                admin2.setMonthtotal(manufactorStatistics.getMonthtotal());
                admin2.setTotal(manufactorStatistics.getTotal());
            });
        }

        return result.getTotal() > 0 ? success(page) : fail();
    }

    @RequestMapping("adminPage")
    @ResponseBody
    public ResultDto adminPage(Page<Admin> page, Admin admin) {
        LambdaQueryWrapper<Admin> lambda = new QueryWrapper<Admin>().lambda();
        lambda.ne(Admin::getValid,AdminConstant.NOTVALID);
        if (StringUtils.isNotBlank(admin.getAdminName())) {
            lambda.like(Admin::getAdminName, admin.getAdminName());
        }
        if (admin.getAdminStatus()!=null) {
            lambda.eq(Admin::getAdminStatus, admin.getAdminStatus());
        }
        lambda.between(Admin::getAdminStatus,AdminConstant.position.DEALER,AdminConstant.position.LANDLORD);
        lambda.orderByAsc(Admin::getAdminStatus);
        IPage<Admin> result = adminService.page(page, lambda);
        result.getRecords().forEach(admin1 -> {
            if(admin1.getAdminStatus()==AdminConstant.position.DEALER){
                admin1.setManufacturersName(adminService.getById(admin1.getManufacturersId()).getAdminName());
            }
        });
        return result.getTotal() > 0 ? success(page) : fail();
    }

    @RequestMapping("select/list")
    @ResponseBody
    public ResultDto getAdminLists() {
        LambdaQueryWrapper<Admin> lambda = new QueryWrapper<Admin>().lambda();
        if(TokenManager.getToken().getAdmin().getAdminStatus()==AdminConstant.position.MANUFACTURERS){
            lambda.eq(Admin::getManufacturersId,TokenManager.getToken().getAdminId());
        }
        lambda.eq(Admin::getAdminStatus,AdminConstant.position.DEALER);
        List<Admin> list = adminService.list(lambda);
        return list.size() > 0 ? success(list) : fail();
    }

    @RequestMapping("change/password")
    @ResponseBody
    public ResultDto changePassword(String oldPassword,String newPassword){
        String adminId = TokenManager.getToken().getAdminId();
        Admin byId = adminService.getById(adminId);
        if(byId.getPassword().equals(oldPassword)){
            byId.setPassword(newPassword);
            adminService.updateById(byId);
        }else{
            return fail("旧密码错误，请确认！");
        }
        return success();
    }
    @RequestMapping("landlordPage")
    @ResponseBody
    public ResultDto landlordPage(MyPage<Ammeter> page){
        LambdaQueryWrapper<Ammeter> lambda=new LambdaQueryWrapper<>();
        lambda.select(Ammeter::getAdminId,Ammeter::getManagerId);
        lambda.eq(Ammeter::getAdminId, TokenManager.getToken().getAdminId());
        lambda.eq(Ammeter::getStatus, AmmeterConstant.ACTIVATE);
        lambda.groupBy(Ammeter::getManagerId);
        IPage<Ammeter> page1 = ammeterService.page(page,lambda);
//        IPage<Ammeter> page1 = ammeterService.groupByPage(TokenManager.getToken().getAdminId(),AmmeterConstant.ACTIVATE,page);

        List<Ammeter> records = page1.getRecords();
        records.forEach(ammeter -> {
            LambdaQueryWrapper<Admin> lambda1 = new QueryWrapper<Admin>().lambda();
            lambda1.eq(Admin::getAdminId,ammeter.getManagerId());
            ammeter.setAdminName(adminService.getOne(lambda1).getAdminName());
            ammeter.setMobilephone(adminService.getOne(lambda1).getMobilephone());
            ammeter.setEmail(adminService.getOne(lambda1).getEmail());
            ammeter.setSex(adminService.getOne(lambda1).getSex());
            ammeter.setIdentity(adminService.getOne(lambda1).getIdentity());
        });

        return page1.getTotal() > 0 ? success(page) : fail();
    }
    //经销商电表分页查询
    @RequestMapping("dealer/info")
    @ResponseBody
    public ResultDto dealer(Page<Ammeter> page){
        LambdaQueryWrapper<Ammeter> lambda = new QueryWrapper<Ammeter>().lambda();
        lambda.eq(Ammeter::getStatus, AmmeterConstant.ACTIVATE);

        lambda.groupBy(Ammeter::getManagerId);
        IPage<Ammeter> page1 = ammeterService.page(page, lambda);

        List<Ammeter> records = page1.getRecords();
        records.forEach(ammeter -> {
            LambdaQueryWrapper<Admin> lambda1 = new QueryWrapper<Admin>().lambda();
            lambda1.eq(Admin::getAdminId,ammeter.getManagerId());
            ammeter.setAdminName(adminService.getOne(lambda1).getAdminName());
            ammeter.setEmail(adminService.getOne(lambda1).getEmail());
            ammeter.setMobilephone(adminService.getOne(lambda1).getMobilephone());
            ammeter.setSex(adminService.getOne(lambda1).getSex());
            ammeter.setIdentity(adminService.getOne(lambda1).getIdentity());
        });
        return page1.getTotal() > 0 ? success(page) : fail();
    }

    @RequestMapping("manager/info")
    @ResponseBody
    public ResultDto managerInfo(Page<Ammeter> page){
        LambdaQueryWrapper<Ammeter> lambda = new QueryWrapper<Ammeter>().lambda();
        lambda.ne(Ammeter::getStatus, AmmeterConstant.ACTIVATE);

        lambda.groupBy(Ammeter::getManagerId);
        IPage<Ammeter> page1 = ammeterService.page(page, lambda);

        List<Ammeter> records = page1.getRecords();
        records.forEach(ammeter -> {
            LambdaQueryWrapper<Admin> lambda1 = new QueryWrapper<Admin>().lambda();
            lambda1.eq(Admin::getAdminId,ammeter.getManagerId());
            ammeter.setAdminName(adminService.getOne(lambda1).getAdminName());
            ammeter.setEmail(adminService.getOne(lambda1).getEmail());
            ammeter.setMobilephone(adminService.getOne(lambda1).getMobilephone());
            ammeter.setSex(adminService.getOne(lambda1).getSex());
            ammeter.setIdentity(adminService.getOne(lambda1).getIdentity());
        });

        return page1.getTotal() > 0 ? success(page) : fail();
    }
    @RequestMapping("manager/detail/info")
    @ResponseBody
    public ResultDto managerDetailInfo(Page<Ammeter> page,Ammeter ammeter){
        LambdaQueryWrapper<Ammeter> lambda = new QueryWrapper<Ammeter>().lambda();
        lambda.eq(Ammeter::getStatus, AmmeterConstant.ACTIVATE);
        lambda.eq(Ammeter::getManagerId,ammeter.getManagerId());
        if(StringUtils.isNotBlank(ammeter.getAdminId()))
            lambda.eq(Ammeter::getAdminId,ammeter.getAdminId());
        IPage<Ammeter> page1 = ammeterService.page(page, lambda);
        List<Ammeter> records = page1.getRecords();
        records.forEach(ammeter1 -> {
            LambdaQueryWrapper<Admin> lambda1 = new QueryWrapper<Admin>().lambda();
            lambda1.eq(Admin::getAdminId,ammeter1.getAdminId());
            ammeter1.setAdminName(adminService.getOne(lambda1).getAdminName());
        });

        return page1.getTotal() > 0 ? success(page) : fail();
    }

    @RequestMapping("reset/password")
    @ResponseBody
    public ResultDto resPassword(Admin admin){
        admin.setPassword(MD5Utils.string2MD5("123456"));
        adminService.updateById(admin);
        return success();
    }
    @RequestMapping("get/adminId")
    @ResponseBody
    public ResultDto getAdminId(){
        System.out.println("adminId:"+TokenManager.getToken().getAdminId());
        if(TokenManager.getToken().getAdmin().getAdminStatus()==AdminConstant.position.MANUFACTURERS){
            return success();
        }
        String stringCode = AdminController.getStringCode();
        LambdaQueryWrapper<Admin> lambda = new QueryWrapper<Admin>().lambda();
        lambda.eq(Admin::getAdminId,stringCode);
        Admin one = adminService.getOne(lambda);
        while(one!=null){
            stringCode = AdminController.getStringCode();
            lambda.eq(Admin::getAdminId,stringCode);
            one = adminService.getOne(lambda);
        }
        return success(stringCode);
    }

    public static String getStringCode(){
        Random random = new Random();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            result.append(random.nextInt(10));
        }
        return result.toString();
//        return "0000";
    }
}
